package system

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
	"woo-server/coms/structs"
	"woo-server/coms/utils"
	"woo-server/models/api"
	"woo-server/models/db/system"
)

// 结构
type UserSvr struct {
	*structs.Common
}

// 初始化
func NewUserService(com *structs.Common) *UserSvr {
	return &UserSvr{com}
}

// 当前用户信息
func (u *UserSvr) GetLoginUserInfo() *api.ResultEntity {
	type Animal struct {
		category string
	}
	//data := api.LoginUser{
	//	UserId: u.Claim.UserId,
	//	RoleId: u.Claim.RoleId,
	//	Name:   u.Claim.Name,
	//	Avatar: u.Claim.Avatar,
	//}
	uModel := system.NewUsers(u.Common)
	uModel.AdminUserId = u.Claim.UserId
	data, err := uModel.First(true)
	if err != nil {
		api.Error(err.Error())
	}
	return api.SuccessToJson(data, "success")
}

// 添加用户信息
func (u *UserSvr) CreateUser() *api.ResultEntity {

	rsp := api.CreateUserRsp{}

	// 参数
	req, err := u.validationCreateUser()
	if err != nil {
		// 日志
		utils.LogError("CreateUser.validationCreateUser err:%s", err.Error())
		return api.BadRequestResultEntity(err.Error())
	}

	// 数据入库
	uModel := system.NewUsers(u.Common)
	uModel.NickName = req.NickName
	uModel.Status = 1
	// 基础参数
	uModel.SetCreateInfo(u.Claim.UserId)

	// 执行创建
	err = uModel.Create()
	if err != nil {
		// 日志
		utils.LogError("CreateUser.Create err:%s", err.Error())
		return api.InternalErrorResultEntity(err.Error())
	}

	// 添加的ID
	rsp.ID = uModel.AdminUserId

	return api.SuccessToJson(utils.ToJson(&rsp), "添加用户成功!")
}

// 校验添加用户信息入参
func (u *UserSvr) validationCreateUser() (*structs.CreateUserReq, error) {

	rsp := &structs.CreateUserReq{}

	// Context
	context := u.Context

	// 参数
	AdminUserId := uint64(structs.SetInt(context.PostForm("AdminUserId")))

	// 内容为空
	if AdminUserId == 0 {
		return rsp, errors.New("缺少必要参数: AdminUserId")
	}
	// 参数
	NickName := context.PostForm("NickName")

	// 内容为空
	if len(NickName) == 0 {
		return rsp, errors.New("昵称不能为空")
	}
	rsp.Status = structs.SetInt(context.PostForm("Status"))
	rsp.NickName = NickName
	rsp.AdminUserId = AdminUserId
	rsp.AdminRoleId = uint64(structs.SetInt(context.PostForm("AdminRoleId")))
	rsp.Email = context.PostForm("Email")
	rsp.FileId = uint64(structs.SetInt(context.PostForm("FileId")))
	return rsp, nil
}

func (u *UserSvr) GetUserConfig() *api.ResultEntity {
	userConfig := system.NewUsers(u.Common).GetUserConfig()
	return api.SuccessToJson(userConfig, "获取用户配置成功!")
}

func (u *UserSvr) UpdateUserInfo() *api.ResultEntity {
	userModel := system.NewUsers(u.Common)
	req, err := u.validationCreateUser()
	if err != nil {
		return api.Error(err.Error())
	}

	userModel.AdminUserId = u.Claim.UserId
	userModel, fErr := userModel.First(false)
	if fErr != nil {
		return api.Error("非法操作!")
	}
	userModel.FileId = 0
	userModel.SetUpdateInfo(u.Claim.UserId)
	//userModel.AdminUserId = req.AdminUserId
	userModel.NickName = req.NickName
	userModel.Email = req.Email
	userModel.FileId = req.FileId
	fmt.Println(userModel)
	SaveErr := userModel.Save()
	if SaveErr != nil {
		return api.Error(SaveErr.Error())
	}
	return api.Success("个人资料更新成功!")
}
func (u *UserSvr) ReloadRole() *api.ResultEntity {
	// 实例化菜单模型
	menuModel := system.NewMenus(u.Common)
	treeList, list := []structs.AdminMenus{}, []system.AdminMenus{}
	// 拼接Redis键值名
	RDSKey := "RoleMenuList_" + strconv.FormatInt(int64(u.Claim.RoleId), 10)
	// roleId = 1 是超级管理员 拥有所有权限菜单
	if u.Claim.RoleId == 1 {
		treeList, list = menuModel.GetAllMenu(false)
	} else {
		// 获取角色菜单id合集
		roleModel := system.NewRole(u.Common)
		role := roleModel.GetFirst("admin_role_id = ?", u.Claim.RoleId)
		//我也不知道为什么直接给数据库 类型设置为[]uint8 会不行 查询的时候会数字全变了. 必须要字符串出来再转int数组才行
		var adminMenuId []int
		err := json.Unmarshal([]byte("["+role.AdminMenuId+"]"), &adminMenuId)
		if err != nil {
			log.Fatal(err)
		}

		treeList, list = menuModel.GetRoleMenu("admin_menu_id in ?", adminMenuId, false)
	}
	// 保存非树状权限菜单
	utils.RedisClient.Set(RDSKey+"_noTree", utils.ToJson(list), 0)
	// 保存树状权限菜单
	utils.RedisClient.Set(RDSKey, utils.ToJson(treeList), 0)
	return api.SuccessToJson(treeList, "登录成功1!")
}

// 用户列表
func (u *UserSvr) GetList(context *gin.Context) *api.ResultEntity {

	search := context.Query("search")
	page := structs.SetInt(context.Query("page"))
	pageSize := structs.SetInt(context.Query("pageSize"))
	Model := system.NewUsers(u.Common)
	list, total := Model.GetListAndTotal(search, page, pageSize)
	result := map[string]interface{}{"list": list, "total": total}
	return api.SuccessToJson(result, "用户列表获取成功!")
}

func (u *UserSvr) PostSave(context *gin.Context) *api.ResultEntity {
	userModel := system.NewUsers(u.Common)
	req, err := u.validationCreateUser()
	if err != nil {
		return api.Error(err.Error())
	}

	userModel, fErr := userModel.First(false)
	if fErr != nil {
		return api.Error("非法操作!")
	}
	userModel.FileId = 0
	userModel.SetUpdateInfo(u.Claim.UserId)
	userModel.AdminUserId = req.AdminUserId
	userModel.NickName = req.NickName
	userModel.Email = req.Email
	userModel.FileId = req.FileId
	userModel.Status = req.Status
	fmt.Println(userModel)
	SaveErr := userModel.Save()
	if SaveErr != nil {
		return api.Error(SaveErr.Error())
	}
	if req.AdminUserId == 0 {
		// 基础参数
		userModel.SetCreateInfo(u.Claim.UserId)
		// 执行创建
		err = userModel.Create()
	} else {
		userModel.AdminRoleId = req.AdminRoleId
		userModel.SetUpdateInfo(u.Claim.UserId)
		err = userModel.Save()
	}
	if err != nil {
		// 日志
		utils.LogError("新增用户报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("success")
}

func (u *UserSvr) Delete(context *gin.Context) *api.ResultEntity {
	//context.Param()
	// 接收POST参数
	AdminRoleId := context.PostForm("AdminRoleId")
	// 校验参数
	if AdminRoleId == "" {
		return api.Error("ID不能为空!")
	}
	if AdminRoleId == "1" {
		api.Error("无法删除超级管理员")
	}
	// 实例化数据库
	Model := system.NewUsers(u.Common)
	// 执行删除
	Model.AdminRoleId = uint64(structs.SetInt(AdminRoleId))
	// 删除数据
	err := Model.Delete()
	if err != nil {
		utils.LogError("删除用户报错:%s", err.Error())
		return api.Error(err.Error())
	}
	return api.Success("删除成功")
}
